<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {
	
	const LOGIN_TOKEN = "loginToken";
	
	private $_id;

	public function authenticate(){
		$user = Users::model()->findByAttributes( array('username'=> $this->username ) );
		
		if( $user === null )
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		else if( $user->password !== md5( $this->password ) )
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		else{
			$this->errorCode = self::ERROR_NONE;
			$this->_id = $user->idUser;
			$this->setState( 'loginTime', date( 'Y-m-d H:i:s' ) );
			$this->setState( 'username', $user->username );
			
			/* Get current season */
			$this->setState( 'currentSeason', Journeys::model()->findByAttributes( array( 'current' => 1 ) )->idJourney );
			
			/* Get current journey */
			$this->setState( 'currentJourney', Seasons::model()->findByAttributes( array( 'current' => 1 ) )->idSeason );
			
			/* Tournament by default will be the first to show */
			$TByDefault = TournamentsUsers::model()->findByAttributes( ['idUser' => $this->_id, 'byDefault' => '1'] );
			$this->setState( 'currentTournament', $TByDefault ? $TByDefault->idTournament : null  );
			
			/* Get Current league of current tournament */
			$this->setState( 'currentLeague', 
					Tournaments::model()->findByPk( [ 'idTournament' => $TByDefault->idTournament ] )->idLeague );
			
			/* Generate a login token and save it in the DB */
			$user->loginToken = md5( date( 'Y-m-d H:i:s' ).$user->username );
			$user->save();
			
			/* Set the same login token in a Cookie */
			$cookieToken = new CHttpCookie( self::LOGIN_TOKEN, $user->loginToken );
			$cookieToken->expire = time() + Yii::app()->params['rememberMeTime'];
			Yii::app()->request->cookies[ self::LOGIN_TOKEN ] = $cookieToken;
		}
		
		return !$this->errorCode;
	}

	public function getId(){
		return $this->_id;
	}
}
